package deng.hibernate.test.collection.valuetype;

import java.util.*;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateSessionMainElement {
	
	private Session session;
	
	public static void main(String[] args) {
		new HibernateSessionMainElement().run();
	}
	
	public void run() {
		Configuration cfg = new Configuration();
		
		// Extra config per this package only.
		Properties extraProperties = new Properties();
		extraProperties.setProperty("hibernate.hbm2ddl.auto", "create");
		cfg.addProperties(extraProperties);
		String resourceName = getClass().getPackage().getName().replaceAll("\\.", "/");
		resourceName += "/HibernateSessionMainElement.hbm.xml";
		cfg.addResource(resourceName);
		
		SessionFactory sf = cfg.configure().buildSessionFactory();
		session = sf.getCurrentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			runExample();
			tx.commit();
		} catch (Throwable e) {
			tx.rollback();
			throw new RuntimeException(e);
		} finally {
			sf.close();
		}
	}

	private void runExample() {
		runCreateData();
		runQuery();
	}
	
	private void runCreateData() {
		runCreateDataProduct("Baby Bottle", 2);
		runCreateDataProduct("Baby High Chair", 1);
		runCreateDataProduct("Baby Diapers", 5);
	}
	
	private void runCreateDataProduct(String name, int numOfImages) {
		ProductStringImage product = new ProductStringImage();
		product.setName(name);
		List<String> images = product.getImages();
		for (int i = 0; i < numOfImages; i++) {
			images.add(product.getName() + "/image" + i);		
		}
		session.persist(product);
	}

	private void runQuery() {
		List<?> resultList = session.createQuery("from ProductStringImage e").list();
		println(resultList);
	}

	public static void println(List<?> list) {
		ToStringStyle style = ToStringStyle.MULTI_LINE_STYLE;
		for (Object object : list) {
			String s = ToStringBuilder.reflectionToString(object, style);
			System.out.println(s);
		}
	}
	
}
